package com.imooc.activiti;

import com.google.common.collect.Maps;
import org.activiti.engine.*;
import org.activiti.engine.form.FormProperty;
import org.activiti.engine.impl.form.DateFormType;
import org.activiti.engine.impl.form.StringFormType;
import org.activiti.engine.repository.Deployment;
import org.activiti.engine.repository.ProcessDefinition;
import org.activiti.engine.runtime.ProcessInstance;
import org.activiti.engine.task.Task;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.time.*;
import java.time.format.DateTimeFormatter;
import java.util.*;


/**
 * 启动类
 *
 * @author lynn
 * @date 18-12-22 下午5:32
 */
public class Main {

    private static final Logger LOGGER = LoggerFactory.getLogger(Main.class);

    public static void main(String[] args) {

        LOGGER.info("启动我们的程序");

        //创建流程引擎
        ProcessEngine processEngine = getProcessEngine();

        //部署流程定义文件
        ProcessDefinition processDefinition = getProcessDefinition(processEngine);

        //启动运行流程
        ProcessInstance processInstance = getProcessInstance(processEngine, processDefinition);

        //处理流程任务
        processTask(processEngine, processInstance);

        LOGGER.info("结束我们的程序");


    }

    private static void processTask(ProcessEngine processEngine, ProcessInstance processInstance) {
        Scanner scanner = new Scanner(System.in);

        while (Objects.nonNull(processInstance) && !processInstance.isEnded()) {

            TaskService taskService = processEngine.getTaskService();
            List<Task> taskList = taskService.createTaskQuery().list();
            for (Task task : taskList) {
                LOGGER.info("待处理的任务 {}", task.getName());
                List<FormProperty> formProperties = processEngine.getFormService().getTaskFormData(task.getId()).getFormProperties();

                Map<String, Object> variables = getTaskVariablesMap(scanner, formProperties);

                taskService.complete(task.getId(), variables);
                processInstance = processEngine.getRuntimeService().createProcessInstanceQuery().processInstanceId(processInstance.getId()).singleResult();

            }
            LOGGER.info("待处理任务数量 {}", taskList.size());

        }

        scanner.close();
    }

    private static Map<String, Object> getTaskVariablesMap(Scanner scanner, List<FormProperty> formProperties) {
        Map<String, Object> variables = Maps.newHashMap();

        formProperties.forEach(prop -> {
            if (StringFormType.class.isInstance(prop.getType())) {

                LOGGER.info("请输入 {} ?", prop.getName());
                String line = scanner.nextLine();
                LOGGER.info("您输入的内容是 [{}]", line);
                variables.put(prop.getId(), line);

            } else if (DateFormType.class.isInstance(prop.getType())) {

                LOGGER.info("请输入 {} ? 格式(yyyy-MM-dd)", prop.getName());
                String line = scanner.nextLine();
                Date date = Date.from(LocalDate.parse(line, DateTimeFormatter.ofPattern("yyyy-MM-dd")).atStartOfDay(ZoneId.systemDefault()).toInstant());
                LOGGER.info("您输入的内容是 [{}]", date);
                variables.put(prop.getId(), date);

            } else {

                LOGGER.info("类型暂不支持 {}", prop.getType());

            }
        });
        return variables;
    }

    private static ProcessInstance getProcessInstance(ProcessEngine processEngine, ProcessDefinition processDefinition) {
        RuntimeService runtimeService = processEngine.getRuntimeService();
        ProcessInstance processInstance = runtimeService.startProcessInstanceById(processDefinition.getId());
        LOGGER.info("启动流程 {}", processInstance.getProcessDefinitionKey());
        return processInstance;
    }

    private static ProcessDefinition getProcessDefinition(ProcessEngine processEngine) {
        RepositoryService repositoryService = processEngine.getRepositoryService();
        Deployment deployment = repositoryService.createDeployment().addClasspathResource("second_approve.bpmn20.xml").deploy();

        ProcessDefinition processDefinition = repositoryService.createProcessDefinitionQuery().deploymentId(deployment.getId()).singleResult();
        LOGGER.info("流程定义文件 {},流程ID {}", processDefinition.getName(), processDefinition.getId());
        return processDefinition;
    }

    private static ProcessEngine getProcessEngine() {
        ProcessEngineConfiguration configuration = ProcessEngineConfiguration.createStandaloneInMemProcessEngineConfiguration();
        ProcessEngine processEngine = configuration.buildProcessEngine();
        LOGGER.info("流程引擎名称 {},版本 {}", processEngine.getName(), ProcessEngine.VERSION);
        return processEngine;
    }

}
